/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2024-09-11 21:41:53
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2024-09-11 21:52:53
 * @FilePath: \projecte:\学习\react\my-react-frameworke\src\components\Menu\menu.tsx
 * @Description: 
 */
import React, { createContext, useState } from 'react'
import classNames from 'classnames'


type MenuMode = 'horizontal' | 'vertical'
type SelectCallback = (index: number) => void

interface IMenuContext {
    index: number;
    onSelect?: SelectCallback;
}

export const MenuContext = createContext<IMenuContext>({ index: 0 })

export interface MenuProps {
    mode?: MenuMode;
    defaultIndex?: number;
    className?: string;
    style?: React.CSSProperties;
    onSelect?: SelectCallback;
    children?: React.ReactNode;
}
const Menu: React.FC<MenuProps> = (props) => {
    const { mode, defaultIndex, className, style, children, onSelect } = props
    const [currentActive, setActive] = useState(defaultIndex)
    const classes = classNames('menu', className, {
        'menu-vertical': mode === 'vertical',
        'menu-horizontal': mode !== 'vertical'
    })
    const handleClick = (index: number) => {
        setActive(index)
        onSelect && onSelect(index)
    }
    const index = typeof currentActive === 'string' ? parseInt(currentActive, 10) : currentActive;
    const passedContext: IMenuContext = {
        // mode: mode,
        index: index || 0,
        onSelect: handleClick,
    }
    return (
        <ul className={classes} style={style}>
            <MenuContext.Provider value={passedContext}>
                {children}
            </MenuContext.Provider>
        </ul>
    )
}

export default Menu